<template>
  <!-- 顶部导航栏 -->
  <a-page-header
    :style="{ background: 'var(--color-bg-2)' }"
    :show-back="false"
    title="我的体重管理"
  >
    <template #extra>
      <a-button type="primary" @click="handleClickAdd">记录新数据</a-button>
    </template>
  </a-page-header>

  <div class="content">
    <!-- 表格数据 -->
    <a-table :data="data">
      <template #columns>
        <a-table-column
          v-for="column in columns"
          :title="column.title"
          :data-index="column.dataIndex"
          :sortable="column.sortable"
          :key="column.dataIndex"
        ></a-table-column>
        <a-table-column title="操作">
          <template #cell="{ record }">
            <a-button @click="() => handleClickDelete(record)">删除</a-button>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </div>

  <!-- modal -->
  <a-modal v-model:visible="showAddModal" @ok="handleAddOk">
    <template #title> 添加新纪录 </template>
    <div>
      <a-form :model="form">
        <a-form-item field="time" label="时间">
          <a-date-picker show-time format="YYYY-MM-DD HH:mm:ss" v-model="form.time" />
        </a-form-item>
        <a-form-item field="weight" label="体重(kg)">
          <a-input-number v-model="form.weight" :precision="2" />
        </a-form-item>
        <a-form-item field="size" label="腰围(cm)">
          <a-input-number v-model="form.size" :precision="2" />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { onBeforeMount, reactive, ref } from 'vue'

interface DataItem {
  id: number
  time: string
  weight: number
  size: number
}
const storageId = 'SAVE_MY_WEIGHT_STORE'
const columns = [
  {
    title: '记录时间',
    dataIndex: 'time',
    sortable: {
      sortDirections: ['ascend', 'descend'],
    },
  },
  {
    title: '体重(kg)',
    dataIndex: 'weight',
  },
  {
    title: '腰围(cm)',
    dataIndex: 'size',
  },
]
const showAddModal = ref(false)
const data = reactive<DataItem[]>([])
const form = reactive<DataItem>({
  id: 1,
  time: '',
  weight: 0,
  size: 0,
})

onBeforeMount(() => {
  loadData()
})

function loadData() {
  const storageRawData = localStorage.getItem(storageId)
  if (storageRawData) {
    const storageData = JSON.parse(storageRawData)
    data.push(...storageData)
  }
}

function saveData() {
  localStorage.setItem(storageId, JSON.stringify(data))
}

function handleClickAdd() {
  showAddModal.value = true
}

function handleAddOk() {
  if (data.length > 0) {
    form.id = data[data.length - 1].id + 1
  }
  data.push(form)
  saveData()
}

function handleClickDelete(record: DataItem) {
  const index = data.findIndex((item) => item.id === record.id)
  if (index > -1) {
    data.splice(index, 1)
    saveData()
  }
}
</script>

<style scoped>
.content {
  padding: 20px;
}
</style>
